package com.pocketmenu.persistence;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.pocketmenu.business.Constants;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class ItemIngredientDataSource {
	
		// Database fields	
		private ItemIngredientDataSource h=this;
		  private SQLiteDatabase database;
		  private SQLiteHelper dbHelper;
		  private String[] allColumns = 
			  { SQLiteHelper.COLUMN_ID,
				SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_INGREDIENT,
				SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_ITEM};
		  
		  private SoapPrimitive resultado;
		  private boolean waitingForThread = true;
		  private boolean success = true;
		  
		  public ItemIngredientDataSource(Context context) {
		    dbHelper = new SQLiteHelper(context);
		  }

		  public void open() throws SQLException {
		    database = dbHelper.getWritableDatabase();
		  }

		  public void close() {
		    dbHelper.close();
		  }

		  public ItemIngredient create(int idIngredient, int idItem) {
		    ContentValues values = new ContentValues();
		    values.put(SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_INGREDIENT, idIngredient);
		    values.put(SQLiteHelper.COLUMN_ITEM_INGREDIENT_ID_ITEM, idItem);		    
		    
		    long insertId = database.insert(SQLiteHelper.TABLE_ITEM_INGREDIENT, null,
		        values);
		    
		    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM_INGREDIENT,
		        allColumns, SQLiteHelper.COLUMN_ID + " = " + insertId, null,
		        null, null, null);
		    cursor.moveToFirst();
		    ItemIngredient newTemp = cursorToObject(cursor);
		    cursor.close();
		    return newTemp;
		  }

		  public void delete(ItemIngredient toDelete) {
		    int id = toDelete.getId();
		    System.out.println("ItemIngredient deleted with id: " + id);
		    database.delete(SQLiteHelper.TABLE_ITEM_INGREDIENT, SQLiteHelper.COLUMN_ID
		        + " = " + id, null);
		  }

		  public List<ItemIngredient> getAll() {
		    List<ItemIngredient> listTemp = new ArrayList<ItemIngredient>();

		    Cursor cursor = database.query(SQLiteHelper.TABLE_ITEM_INGREDIENT,
		        allColumns, null, null, null, null, null);

		    cursor.moveToFirst();
		    while (!cursor.isAfterLast()) {
		      ItemIngredient temp = cursorToObject(cursor);
		      listTemp.add(temp);
		      cursor.moveToNext();
		    }
		    // Make sure to close the cursor
		    cursor.close();
		    return listTemp;
		  }

		  private ItemIngredient cursorToObject(Cursor cursor) {
		    ItemIngredient temp = new ItemIngredient();
		    temp.setId(cursor.getInt(0));
		    temp.setIdIngredient(cursor.getString(1));
		    temp.setIdItem(cursor.getString(2));		    
		    return temp;
		  }		  		  
		  
		  public boolean loadFromWeb(){
			  Thread networkThread = new Thread() {
	      	    @Override
	      	    public void run() {
		      	      
		  	    	//request       	    
		      	    String metodo = "select";	
		      	    SoapObject request= new SoapObject(Constants.namespace, metodo);
		      	    request.addProperty("tabla", "ItemIngredient");
		
		      	    //modelo sobre
		      	    SoapSerializationEnvelope sobre= new SoapSerializationEnvelope(SoapEnvelope.VER11);
		      	    sobre.dotNet = true;
		
		      	    sobre.setOutputSoapObject(request);
		
		      	    //transporte
		      	    HttpTransportSE transporte= new HttpTransportSE(Constants.url,10000);	          
		      	    transporte.debug = true;           
		
		      	    //llamada
		      	    try {
		      	    	transporte.call(Constants.namespace+metodo, sobre);
			   			
			   			//resultado
			   			resultado = (SoapPrimitive) sobre.getResponse();	   					   			
				   		success = true;
				   		
			   			} catch (Exception e) {
		   					Log.i("App.err" + getClass().getSimpleName(), e.getMessage());
			   				e.printStackTrace();
			   				success = false;
			   			}
		      	    waitingForThread = false;
	      	    }	      	      
	  	    };
	  	    networkThread.start();
	  	    
	  	    while(waitingForThread){	      	    	
	  	    }
	  	    
	  	    if(success)
	  	    	return loadDataToDatabase();
	  	    else
	  	    	return false;
		  }
		  
		  private boolean loadDataToDatabase()
		  {
			  try
			  {						
				String respuesta = resultado.toString();				
				String[] restaurantesWeb = respuesta.split(";");				
					
				database.execSQL("DROP TABLE IF EXISTS " + SQLiteHelper.TABLE_ITEM_INGREDIENT);
				database.execSQL(SQLiteHelper.TABLE_CREATE_ITEM_INGREDIENT);				
				
	   			for(int i=0;i<restaurantesWeb.length;i++){
	   				String[] restauranteWebActual = restaurantesWeb[i].split("\\*");
	   				h.create(Integer.parseInt(restauranteWebActual[1]),Integer.parseInt( restauranteWebActual[2]));
	   			}
				success = true;
				Log.i("App.log " + getClass().getSimpleName(), "Exito");
			  }
			  catch(Exception e)
			  {
				  Log.i("App.err " + getClass().getSimpleName(), e.getMessage());
				  e.printStackTrace();
				  success = false;
			  }
			  
			  return success;
		  }	  		  
}
